/* eslint no-useless-escape: 0 */
/* eslint one-var: 0 */
export default {
  setData: function (name, data, isSession) {
    const method = isSession ? 'sessionStorage' : 'localStorage'
    const item = typeof data === 'object' ? JSON.stringify(data) : data
    try {
      if (window[method]) {
        window[method][name] = item
      }
    } catch (e) {
      console.log(e)
    }
  },
  getData: function (name, isSession) {
    const method = isSession ? 'sessionStorage' : 'localStorage'
    if (this.hasData(name, isSession)) {
      try {
        return JSON.parse(window[method][name])
      } catch (e) {
        // ..
      }
      return window[method][name]
    }
    return null
  },
  hasData: function (name, isSession) {
    const method = isSession ? 'sessionStorage' : 'localStorage'
    try {
      if (window[method] && window[method][name]) {
        return true
      }
    } catch (e) {
      console.log(e)
    }
    return false
  },
  removeData: function (name, isSession) {
    const method = isSession ? 'sessionStorage' : 'localStorage'
    try {
      if (window[method] && window[method][name]) {
        window[method].removeItem(name)
      }
    } catch (e) {
      console.log(e)
    }
  },
  clearData: function (isSession) {
    const method = isSession ? 'sessionStorage' : 'localStorage'
    try {
      if (window[method]) {
        window[method].clear()
      }
    } catch (e) {
      console.log(e)
    }
  },
  addItem: function (name, data, pos, isSession) {
    const method = isSession ? 'sessionStorage' : 'localStorage'
    try {
      if (window[method]) {
        let queue
        if (!this.hasData(name, isSession)) {
          queue = []
        } else {
          queue = this.getData(name, isSession)
        }
        if (pos && pos === 'start') {
          queue.unshift(data)
        } else {
          queue.push(data)
        }
        this.setData(name, queue, isSession)
      }
    } catch (e) {
      console.log(e)
    }
  },
  getItem: function (name, idx, isSession) {
    const queue = this.getData(name, isSession)
    if (queue && queue[idx]) {
      return queue[idx]
    }
    return null
  }
}
